package net.kleinhenz.droidshop;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import net.kleinhenz.droidshop.model.Message;
import net.kleinhenz.droidshop.model.Motd;
import net.kleinhenz.droidshop.model.Product;
import net.kleinhenz.droidshop.scanner.CaptureActivity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

public class DroidShop extends Activity 
{
	public static final String APP_NAME = "DroidShop";
	public static final String PREFS_NAME = "DroidShopPrefsFile";
	public static final Map<String, Double> currency = new HashMap<String, Double>();

	public static int MENUITEM_HISTORY = 0;
	public static int MENUITEM_WISHLIST = 1;
	public static int MENUITEM_ABOUT = 2;

	private static Motd motd = null;
	private static String ipAddress = null;
	private static String client = null;

	private List<Product> productList = null;
	private ProgressDialog progressDialog = null;
	private ProgressBar progressBar = null;
	private ProductInfoThread productInfoThread = null;
	private MotdThread motdThread = null;
		
	private Handler handler = new Handler() {
	    @Override
        public void handleMessage(android.os.Message msg) 
	    {
	    	if (msg.what==ProductInfoThread.ERROR_PARSING)
	    	{
		    	progressDialog.dismiss();
				showError(getResources().getString(R.string.error_parsing));
		    	productInfoThread = null;
	    	}
	    	else if (msg.what==ProductInfoThread.ERROR_RETRIEVING)
	    	{
		    	progressDialog.dismiss();
				showError(getResources().getString(R.string.error_loading));
		    	productInfoThread = null;
	    	}
	    	else if (msg.what==ProductInfoThread.OK)
	    	{
		    	progressDialog.dismiss();
				productList = productInfoThread.getResult();
				Log.d("DroidShop", "Got productList. Entries: " + (productList==null?0:productList.size()));				
				
				if (productList==null || productList.isEmpty())
				{
					Log.d("DroidShop", "No result.");				
					showError(getResources().getString(R.string.no_match));
				}
				else
				{					
					Log.d("DroidShop", "Starting tabbed product activity.");				
					Intent droidShopTabsIntent = new Intent(DroidShop.this, DroidShopTabsActivity.class);
					droidShopTabsIntent.putExtra("product", productList.get(0));
					startActivity(droidShopTabsIntent);
				}
		    	productInfoThread = null;
	    	}
	    	else if (msg.what==MotdThread.ERROR_PARSING)
	    	{
		    	progressDialog.dismiss();
	    		((Button)findViewById(R.id.ScanButton)).setEnabled(false);
	    		((TextView)findViewById(R.id.MotdText)).setText(getResources().getString(R.string.server_down));
	    		motdThread = null;
	    	}
	    	else if (msg.what==MotdThread.ERROR_RETRIEVING)
	    	{
	    		((Button)findViewById(R.id.ScanButton)).setEnabled(false);
	    		((TextView)findViewById(R.id.MotdText)).setText(getResources().getString(R.string.server_down));
	    		motdThread = null;
	    	}
	    	else if (msg.what==MotdThread.OK)
	    	{
	    		progressBar.setVisibility(ProgressBar.INVISIBLE);
	    		
	    		motd = motdThread.getResult();
	    		((Button)findViewById(R.id.ScanButton)).setEnabled(true);
	    		TextView motdTextView = (TextView)findViewById(R.id.MotdText);
	    		for (Message motdMessage : motd.getMessages())
				{
					if (getResources().getString(R.string.locale).equals(motdMessage.getLocale()))
						motdTextView.setText(motdMessage.getText());
				}
	    		motdThread = null;
	    	}
        }
	};
	
	private void initiateScan()
	{
		Intent intentScan = new Intent(CaptureActivity.INTENT_SCAN_ACTION);
	    intentScan.addCategory(Intent.CATEGORY_DEFAULT);
	    try {
	      this.startActivityForResult(intentScan, 0x0ba7c0de);
	    } catch (ActivityNotFoundException e) {
	    	// FIXME: proper dialog
	    	throw new RuntimeException(e);
	    }
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		
		SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
	    client = settings.getString("client", createClient()).replace('%', '_');
		
		this.setContentView(R.layout.main);
		
		ipAddress = retrieveIP();

        progressBar = ((ProgressBar)findViewById(R.id.ProgressBar));
        progressBar.setIndeterminate(true);
        progressBar.setVisibility(ProgressBar.VISIBLE);
        
        Button scanButton = ((Button)findViewById(R.id.ScanButton));
        scanButton.setEnabled(false);

        motdThread = new MotdThread(this, handler);
        motdThread.start();		
		
        scanButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) 
			{
				Log.d("DroidShop", "Scanning.");			
				if (inDebugMode())
					onActivityResult(0, 0, null);
				else
					initiateScan();
			}
		});
	}
	
	@Override
    protected void onStop()
	{
		super.onStop();
    
		SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
		SharedPreferences.Editor editor = settings.edit();
		editor.putString("client", client);
		editor.commit();
    }

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    super.onCreateOptionsMenu(menu);
	    menu.clear();
	    menu.add(0, MENUITEM_WISHLIST, 0, R.string.menu_wishlist)
	        .setIcon(android.R.drawable.ic_menu_agenda);
	    menu.add(0, MENUITEM_HISTORY, 1, R.string.menu_history)
        	.setIcon(android.R.drawable.ic_menu_compass);
	    menu.add(0, MENUITEM_ABOUT, 3, R.string.menu_about)
        	.setIcon(android.R.drawable.ic_menu_info_details);
	    return true;
	}
	
	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) 
	{
		if (item.getItemId()==MENUITEM_ABOUT)
		{
			new AlertDialog.Builder(this)
            .setTitle(getResources().getString(R.string.about_title))
            .setMessage(getResources().getString(R.string.about).replace("%VERSION%", motd.getVersionMajor() + "." + motd.getVersionMinor() + "." + motd.getVersionMicro()))
            .setPositiveButton(android.R.string.ok, null)
            .show();
		}
		else if (item.getItemId()==MENUITEM_HISTORY)
		{
			Intent listIntent = new Intent(this, ProductListActivity.class);			
			listIntent.putExtra("list", ListFactory.LIST_HISTORY);
			startActivity(listIntent);			
		}
		else if (item.getItemId()==MENUITEM_WISHLIST)
		{
			Intent listIntent = new Intent(this, ProductListActivity.class);
			listIntent.putExtra("list", ListFactory.LIST_WISHLIST);
			startActivity(listIntent);			
		}	
		return true;
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent intent) 
	{
		String resultData = null;
		String resultFormat = null;
		
		if (inDebugMode())
		{
			resultData = "0765344556";
			resultFormat = "EAN-13";
		}
		else
		{
			resultData = intent.getExtras().getString(CaptureActivity.RESULT);
			resultFormat = intent.getExtras().getString(CaptureActivity.RESULT_FORMAT);
		}
		
		Log.d("DroidShop", "Got scan result.");
		if (resultData!=null && resultFormat!=null) 
		{
			// retrieve products
			Log.d("DroidShop", "Got scan result: " + resultData + " " + resultFormat);
			progressDialog = ProgressDialog.show(this, getResources().getString(R.string.working), getResources().getString(R.string.getting_info), true, false);
			
	        productInfoThread = new ProductInfoThread(this, ProductInfoThread.Mode.LOOKUP, resultData, getResources().getString(R.string.locale), handler);
	        productInfoThread.start();		
		}
	}
	
	public void showError(String message)
	{
		new AlertDialog.Builder(this)
        .setTitle(getResources().getString(R.string.error))
        .setIcon(android.R.drawable.ic_dialog_alert)
        .setMessage(message)
        .setPositiveButton(getResources().getString(R.string.scan_again), new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) 
                {
                	initiateScan();
                }
        }).show();
	}
	
	public boolean inDebugMode()
	{
		return getResources().getString(R.string.debug)!=null && getResources().getString(R.string.debug).equals("true");
	}
	
	public static Motd getMotd()
	{
		return DroidShop.motd;
	}
	
	public static String getIPAddress()
	{
		return DroidShop.ipAddress;
	}
	
	public static String getClient()
	{
		return DroidShop.client;
	}
	
	private String createClient()
	{
		return "CL_" + UUID.randomUUID().toString();
	}
	
	private String retrieveIP()
	{
		String ip = null;
        try 
        {
            for (Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces(); ifaces.hasMoreElements();) 
            {
                NetworkInterface iface = ifaces.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = iface.getInetAddresses(); enumIpAddr.hasMoreElements();) 
                {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress()) 
                    {
                    	ip = inetAddress.getHostAddress().toString();
                    }
                }
            }
            return "IP_" + ip;
        } 
        catch (SocketException ex) 
	    {
     	   return null;
	    }
	}
}